package com.duoqin.account.ui;

import android.accounts.Account;
import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.app.Activity;
import android.app.AlertDialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.duoqin.account.DuoqinAccount;
import com.duoqin.account.viewmodel.LoginViewModel;
import com.duoqin.common.ui.AbsActivity;
import com.duoqin.guard.Guard;
import com.duoqin.guard.VerifyGuardCodeHelper;
import com.duoqin.syncassistant.R;
import com.duoqin.syncassistant.SyncAssistantApplication;
import com.duoqin.syncassistant.ui.SyncAssistantActivity;

public class AccountActivity extends AbsActivity {

    private final int REQUEST_LOGIN = 0;
    private final int REQUEST_VERIFY_GUARD_CODE = 1;

    private TextView mAccountTV, mSyncAssistant, mTranslator,mLogout;
    private View mProgressView;
    private AlertDialog mAlertDialog;
    protected BroadcastReceiver mBroadcastReceiver;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_account);
        setupTitle(getString(R.string.duoqin_account_title));
        mProgressView = findViewById(R.id.sync_progress);
        mAccountTV = findViewById(R.id.account_id);
        mLogout = findViewById(R.id.duoqin_logout_btn);
        mLogout.setOnClickListener(this);

        mSyncAssistant = findViewById(R.id.sync_assistant);
        mSyncAssistant.setOnClickListener(this);
        mTranslator = findViewById(R.id.duoqin_translator);
        mTranslator.setOnClickListener(this);

        mBroadcastReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (SyncAssistantApplication.INTENT_ACTION_TOKEN_EXPIRED.equals(action)) {
                    // TODO
                }
            }
        };
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SyncAssistantApplication.INTENT_ACTION_TOKEN_EXPIRED);
        LocalBroadcastManager.getInstance(this).registerReceiver(mBroadcastReceiver, intentFilter);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (SyncAssistantApplication.getsInstance().hasLogin()) {
            mAccountTV.setText(DuoqinAccount.getAccountName(getApplicationContext()));
        } else {
            mAccountTV.requestFocus();
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (mAlertDialog != null && mAlertDialog.isShowing()) {
            mAlertDialog.dismiss();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void onClick(View v) {
//        if (R.id.feature_bar_options == v.getId() || R.id.feature_bar_options_icon == v.getId()) {
//            if (SyncAssistantApplication.getsInstance().hasLogin()) { // to log out
//                attemptLogout();
//            } else {
//                Intent intent = new Intent(DuoqinAccount.INTENT_ACTION_REGISTER);
//                startActivityForResult(intent, REQUEST_LOGIN);
//            }
//        } else if (R.id.feature_bar_center == v.getId()
//                || R.id.feature_bar_center_icon == v.getId()) {
//            if (!SyncAssistantApplication.getsInstance().hasLogin()) {
//                Intent intent = new Intent(DuoqinAccount.INTENT_ACTION_LOGIN);
//                startActivityForResult(intent, REQUEST_LOGIN);
//            }
        if (R.id.sync_assistant == v.getId()) {
            Intent intent = new Intent(this, SyncAssistantActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }else if(R.id.duoqin_logout_btn == v.getId()){
            if (SyncAssistantApplication.getsInstance().hasLogin()) {
                if (Guard.isDuoqinGuardEnable(this)
                        && !VerifyGuardCodeHelper.isCodeVerified(this)) {
                    Intent intent = new Intent("com.duoqin.guard.verifyGuardCode");
                    intent.addCategory(Intent.CATEGORY_DEFAULT);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    startActivityForResult(intent, REQUEST_VERIFY_GUARD_CODE);
                } else {
                    attemptLogout();
                }
            }
        } else {
            super.onClick(v);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d(TAG, "onActivityResult resultCode = " + resultCode
                + "; requestCode = " + requestCode);
        if (RESULT_OK != resultCode) return;

        if (REQUEST_LOGIN == requestCode) {
            if (SyncAssistantApplication.getsInstance().hasLogin()) {
               // TODO
            }
        } else if (REQUEST_VERIFY_GUARD_CODE == requestCode) {
            attemptLogout();
        }
    }

    private void attemptLogout() {
        if (mAlertDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(this)
                    .setMessage(R.string.action_sign_out_confirm)
                    .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ViewModelProviders.of(AccountActivity.this)
                                    .get(LoginViewModel.class).logout(
                                    DuoqinAccount.getAccountToken(getApplicationContext()));
                            // NOTICE: No need to wait response
                            SyncAssistantApplication.getsInstance().clearUserInfo();
//                            mAccountTV.setText(R.string.account_not_login);
//                            mAccountTV.requestFocus();
                            Intent intent = new Intent(AccountActivity.this,SyncAssistantActivity.class);
                            startActivity(intent);
                            finish();
                            //TODO
                        }
                    })
                    .setNegativeButton(android.R.string.cancel, null);
            mAlertDialog = builder.create();
        }
        mAlertDialog.show();
    }

    /**
     * Shows the progress UI and hides the login form.
     */
    private void showProgress(final boolean show) {
        mSyncAssistant.setEnabled(!show);
        mTranslator.setEnabled(!show);

        int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
        mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
        mProgressView.animate().setDuration(shortAnimTime).alpha(
                show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            }
        });
    }
}
